package cc.linker.steplink.crm.controller;

import cc.linker.steplink.crm.dao.TrackDao;
import cc.linker.steplink.crm.domain.Track;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.service.impl.CrmHelperImpl;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;


@Controller
@RequestMapping("/crmhelper")
public class CrmHelpTranController {

    @Autowired
    private CrmHelperImpl crmHelper;

    @Autowired
    private TrackDao trackDao;

    @Value("${system.scrm.wxMatrix}")
    private String wxMatrix;

    @Value("${casclient.clientHost}")
    private String host;

    @RequestMapping("/trans")
    public String trans(
            @RequestParam(value = "id") String id,
            @RequestParam(value = "oauth2_userinfo", required = false) String oauth2_userinfo
    ) throws Exception {
        Map<String, Object> record = crmHelper.get(id);
        if (record == null) {
            throw GlobalException.build("链接无效，已删除");
        }
        String orgId = record.get("orgId").toString();
        String token = crmHelper.getTokenByOrgId(orgId);
        if (token == null) {
            throw GlobalException.build("新增/编辑链接失败，请先前往「设置」关联服务号信息！");
        }
        String labelLinkUrl = host + "/crmhelper/trans?id=" + id;
        String callback = URLEncoder.encode(labelLinkUrl, "UTF-8");
        if (oauth2_userinfo == null) {
            //跳转 微信矩阵
            return "redirect:" + wxMatrix + "index.php?s=/Home/WxService/oauth2_authorize&token=" + token + "&callback=" + callback;
        }
        // 获取用户的信息
        Map userInfo = (Map) JSON.parse(URLDecoder.decode(oauth2_userinfo, "UTF-8"));

        userInfo.put("token", token);
        userInfo.put("orgId", orgId);

        // 用户入库操作  得到customerId
        String customerId = crmHelper.addCustomer(userInfo);

        // 获取标签ids
        String labelIds = record.get("labelIds").toString();
        if (labelIds != null) {
            // 标签和用户关联关系入库
            crmHelper.addLabels(labelIds, customerId);
        }
        String trackRemark = "打开了 " + record.get("linkName").toString();
        Track track = new Track(UUID.randomUUID().toString(),
                customerId, trackRemark, "", null, (byte) 0, "", "open");
        trackDao.insertSelective(track);
        // 跳转原地址
        return "redirect:" + record.get("linkUrl").toString();
    }


}
